package com.yyfax.pay.config.data.service.impl;

import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import com.yyfax.commons.json.JacksonUtil;
import com.yyfax.framework.service.CacheService;
import com.yyfax.framework.service.impl.BaseServiceImpl;
import com.yyfax.pay.common.constants.CacheName;
import com.yyfax.pay.config.data.dao.BankConfigExtDao;
import com.yyfax.pay.config.data.service.BankConfigExtService;
import com.yyfax.pay.config.model.po.BankConfigExtPO;



@Service
public class BankConfigExtServiceImpl extends BaseServiceImpl implements BankConfigExtService {

	private Logger logger = LoggerFactory.getLogger(this.getClass());

	@Autowired
	private BankConfigExtDao bankConfigExtDao;

	public BankConfigExtServiceImpl(@Qualifier("payCacheService") CacheService cacheService) {
		super(cacheService);
	}

	@Override
	public BankConfigExtPO queryByThirdBankCode(String bankCode, String paymentCode) throws Exception {
		if (StringUtils.isBlank(bankCode) || StringUtils.isBlank(paymentCode)) {
			logger.debug("参数bankCode:{},paymentCode:{}，存在空值", bankCode, paymentCode);
			return null;
		}

		return bankConfigExtDao.selectByBankCodeAndPayment(bankCode, paymentCode);
	}

	@Override
	public BankConfigExtPO queryByPaymentAndBankCodeExt(String paymentCode, String thirdBankCode) throws Exception {
		String json = getCache(CacheName.BANK_CONFIG_EXT);
		if (StringUtils.isNotBlank(json)) {
			List<BankConfigExtPO> list = (List<BankConfigExtPO>) JacksonUtil.fromJson(json, List.class, BankConfigExtPO.class);
			for (BankConfigExtPO po : list) {
				if (paymentCode.equals(po.getPaymentCode())&&thirdBankCode.equals(po.getBankCodeExt())) {
					return po;
				}
			}

		}else{
			queryForList();
		}
		
		return bankConfigExtDao.selectByPaymentAndBankCodeExt(paymentCode, thirdBankCode);
	}

	@Override
	public List<BankConfigExtPO> queryForList() throws Exception {
		List<BankConfigExtPO> pos = null;
		String json = getCache(CacheName.BANK_CONFIG_EXT);
		if (StringUtils.isNotBlank(json)) {
			pos = (List<BankConfigExtPO>) JacksonUtil.fromJson(json, List.class, BankConfigExtPO.class);
			return pos;
		}
		logger.info("缓存数据为空从数据库获取银行扩展信息");
		pos = bankConfigExtDao.selectForList();
		if (pos != null && !pos.isEmpty()) {
			cacheService.set(CacheName.BANK_CONFIG_EXT, JacksonUtil.toJson(pos));
		}
		return pos;
	}
}
